package org.example.commmon;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLClientInfoException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局部异常处理
 */

//@ControllerAdvice是拦截声明
//annotations = {RestController.class}是指拦截有RestController的类
@ControllerAdvice(annotations = {RestController.class})
//这个注解能将返回的数据转换成json
@ResponseBody
@Slf4j
public class GlobalExcptionHandler {

    /**
     * SQLIntegrityConstraintViolationException.class是指对这类异常进行处理
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.error(e.getMessage());
        //判断异常是否包含Duplicate entry（这类异常指的是字段重复）
        //Duplicate entry 'admin' for key 'employee.idx_username'
        if (e.getMessage().contains("Duplicate entry")){
            String account = e.getMessage().split(" ")[2];
            return R.error(account+"已存在，添加失败");
        }
        return R.error("未知异常，添加失败");
        }

     @ExceptionHandler(CustomException.class)
         public R<String> exceptionHandler(CustomException ce){
             log.error(ce.getMessage());
             return R.error(ce.getMessage());
         }



}
